/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import i18n from '@src/locales'

/* components */
import CardEditDialog from './CardEditDialog';
import CardViewDialog from './CardViewDialog';
import { MessageBox } from 'element-ui';

/* utils */
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
import { getRootWindow } from '@src/util/dom'
import Log from '@src/util/log'


export default {
  props: {
    task: {
      type: Object,
      default: () => ({})
    },
    card: {
      type: Object,
      default: () => ({})
    },
    taskAllowUpdate: {
      type: Boolean,
      default: true
    },
    shareData:{
      type:Object,
      default:() => ({})
    },
    listLoading: {
      type: Boolean,
      default: false
    },
    // 工单新建入口进入
    isFromCreated: {
      type: Boolean,
      default: false
    },
    // 是否是自定义节点的状态
    customStateNameEnable: {
      type: Boolean,
      default: false
    }
  },
  inheritAttrs: false,
  data() {
    return {
      pending: false,
      cardInstance: {}, // 附加组件实例数据
      action: '',
      needServerDeleFiles:[],
      rowIndex: 0,
      disabledSaveButton: true, // 禁用保存按钮
    }
  },
  computed: {
    collapseDirection() {
      return this.shareData.collapseDirection
    },
    btnStyle() {
      return this.collapseDirection == 'left' ? 'btn-wrap-collapse' : 'btn-wrap-nocollapse'
    },
    /**
     * @description 是否支持工单附加组件导出
     */
    isExport() {
      if(typeof this.card.config === 'string'){
        return JSON.parse(this.card.config || '{}').export
      }else{
        return this.card.config?.export
      }
    },
    /**
     * @description 是否工时记录类型
     */
    isHoursRecord() {
      return this.card.specialfrom == '工时记录';
    },
    /**
     * @description 是老权限，只有两个权限，没有返回canCreate以及canDelete
     */
    isOldAuth() {
      let { canCreate, canDelete } = this.card;
      return canCreate === undefined && canDelete === undefined;
    },
    /**
     * @description 附加组件操作的前提是工单未删除且工单允许编辑
     */
    editable() {
      return this.task.isDelete == 0 && this.taskAllowUpdate;
    },
    /**
     * @description 当前工单节点的附加组件是否可以进行编辑，删除，添加操作
     */
    stateCanEdit() {
      let { state } = this.task;

      // 该附加组件设置处于某种状态下可以编辑
      let stateCanEdit = this.card.stateCanEdit;

      // 没有设置则默认可以
      if (!stateCanEdit || !stateCanEdit.length) return true;

      // 如果设置了，则判断设置的节点是否包含当前工单状态
      /*customStateNameEnable自定义节点判断lastPassedNodeId， 非自定义节点判断工单状态*/
      return (stateCanEdit.indexOf(state) > -1 && !this.customStateNameEnable) || (this.customStateNameEnable && this.task?.attribute?.lastPassedNodeId && stateCanEdit.includes(this.task.attribute.lastPassedNodeId));
    },
    /** 
    * @description 允许新增
    * 1.有新增权限 或者 老权限(无新增和删除)且有编辑权限
    * 2.附加组件设置的允许某种状态下可编辑 或 无设置
    * 3.工单允许修改 isAllowUpdate
    */
    allowCreate() {
      let { canCreate, canWrite } = this.card;
      let hasCreateAuth = canCreate || (this.isOldAuth && canWrite);

      return hasCreateAuth && this.stateCanEdit && this.task.isAllowUpdate;
    },
    /** 
    * @description 允许编辑
    * 1.有编辑权限
    * 2.附加组件设置的允许某种状态下可编辑 或 无设置
    * 3.工单允许修改 isAllowUpdate
    */
    allowEdit() {
      return this.card.canWrite && this.stateCanEdit && this.task.isAllowUpdate;
    },
    /** 
    * @description 允许删除
    * 1.有删除权限 或者 老权限(无新增和删除)且有编辑权限
    * 2.附加组件设置的允许某种状态下可编辑 或 无设置
    */
    allowDelete() {
      let { canDelete, canWrite } = this.card;
      let hasDeleteAuth = canDelete || (this.isOldAuth && canWrite);

      return hasDeleteAuth && this.stateCanEdit;
    },
    editUnitPrice() {
      return this.task?.taskType?.options?.editUnitPrice || false;
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    },
    attachmentFilelds() {
      if(this.card.inputType=='single') return this.fields.filter(item=>item.formType=='attachment') || []

      return this.card.fields.filter(item=>item.formType=='attachment') || []
    },
    needViewDeleteFiles() {
      const needViewDeleteFiles = [];

      if(this.isHoursRecord){
        const attachment =  this.hoursRecordData?.workTimeRecordMainList?.[this.rowIndex]?.attachment || []
        attachment.forEach(i => {
          needViewDeleteFiles.push(i.fileId)
        })
      }else{
        const value = this.card.inputType=='single' ?  this.formValue.attribute : this.value.attribute[this.rowIndex] 

        this.attachmentFilelds.map(item=>{
          value?.[item.fieldName].forEach(i => {
            needViewDeleteFiles.push(i.fileId)  
          })
        })
      }
      return needViewDeleteFiles;
    },
    // 开启添加行灰度
    isShowCardMulti() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.CARD_MULTI_SAVE;
    },
    // 多行新增权限
    canAddMultiRowAuth() {
      return this.isShowCardMulti && this.allowCreate;
    },
    // 多行编辑权限
    canEditMultiRowAuth() {
      return this.isShowCardMulti && this.allowEdit;
    },
  },
  methods: {
    /** 
    * @description 附加组件操作
    * 新增、编辑、详情、删除、位置详情
    */
    handleEvent({ action, cardInstance, rowIndex }) {
      this.action = action;
      this.cardInstance = { attribute: cardInstance || {} };

      if (action == 'create' || action == 'edit') {
        this.rowIndex = rowIndex;
        this.$refs.taskCardEdit.openDialog(rowIndex);
      } else if (action == 'delete') {
        this.deleteCard(cardInstance.id);
        this.rowIndex = rowIndex;
      } else if (action == 'view') {
        this.$refs.taskCardView.openDialog();
      } else if (action == 'location') {
        this.$refs.hoursRecordLocation.openDialog(cardInstance.id);
      }
    },
    /** 
    * @description 导出附加组件操作
    */
    exportEvent() {
      let params ={
        taskId: this.task.id,
        cardId: this.card.cardId
      }
      this.$http.get('/excels/task/cardInfo/export', params, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.card.cardName;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() =>{

      })
    },
    /** 
    * @description 获取接口API
    */
    getApiMap(action) {
      let apiMap = {};

      // 若是工时记录
      if (this.isHoursRecord) {
        apiMap = {
          create: 'createHoursRecord',
          edit: 'updateHoursRecord',
          delete: 'deleteHoursRecord'
        }
      } else {
        apiMap = {
          create: 'taskCreateCard',
          edit: 'taskEditCard',
          delete: 'taskDeleteCard'
        }
      }

      return apiMap[action];
    },
    /**
    * @description 将附加组件数据打包成服务器可接收的数据
    */
    pack(form) {
      let { cardId, inputType } = this.card;

      let data = {
        taskId: this.task.id,
        attribute: {},
        cardId,
        inputType
      }

      if (this.action == 'edit') {
        data.attribute.id = form.id;
        if(this.needServerDeleFiles.length){
          data.deleteFiles = this.needServerDeleFiles
        }
      }
      
      this.card.fields.forEach(field => {
        data.attribute[field.fieldName] = form[field.fieldName];
      })
      
      data = this.globalFormSubmissionDataProcessingHandler(this.card.fields, data)

      // 国际化时间处理
      data = disposeFormSubmitTime(this.card.fields, data)

      return data;
    },
    /**
    * @description 将工时记录数据打包成服务器可接收的数据
    */
    packSpecial(form) {
      let data = {};

      if (this.action == 'edit') {
        data.id = form.id;
        if(this.needServerDeleFiles.length){
          data.deleteFiles = this.needServerDeleFiles
        }
      } else {
        data.cardId = this.card.cardId;
        data.orderId = this.task.id;
        data.recordFromType = 1;
      }
      
      this.formFields.forEach(field => {
        if (field.formType === 'attachment') {
          data[field.fieldName] = JSON.stringify(form[field.fieldName] || '[]');
        } else {
          data[field.fieldName] = form[field.fieldName];
        }
      })

      return data;
    },
    /** 
    * @description 新增、编辑附加组件
    */
    submit(form) {
      if(this.isFromCreated) {
        delete form.attribute;
        if (this.card.inputType=='single') {
          this.value.attribute = form;
        } else {
          if (form.rowIndex !== undefined && form.rowIndex === this.rowIndex) {
            this.value.attribute.splice(form.rowIndex, 1 ,form)
            delete form.rowIndex
          } else {
            this.value.attribute.push(form)
          }
        }
        this.$listeners.loadingOpen(false);
        return;
      }
      // if (this.pending) return;
      // this.pending = true;

      const API = this.getApiMap(this.action);
      // 处理国际化时间转换
      // let formValue = disposeFormSubmitTime( this.isHoursRecord ? this.formFields : this.card.fields , form)
      const params = this.isHoursRecord ? this.packSpecial(form) : this.pack(form);

      TaskApi[API](params).then(res => {
        if (res.success) {
          this.$platform.notification({
            type: 'success',
            title: i18n.t('common.base.saveSuccess')
          })
          this.needServerDeleFiles = []
          this.isHoursRecord ? this.getHoursRecordList() : this.$emit('initData');
          this.$emit('updateInfoRecord');
          // window.location.href = `/task/view/${this.task.id}`;
        } else {
          this.$platform.alert(res.message);
          this.$emit('initData')
          // this.pending = false;
        }
      }).catch(err => {
        // this.pending = false;
      })
    },
    /** 
    * @description 删除附加组件
    */
    async deleteCard(infoId) {
      const API = this.getApiMap('delete');

      try {
        let result = await this.$platform.confirm(i18n.t('task.tip.deleteTip'));
        if (!result) return;
        if(this.isFromCreated && this.card.inputType == 'multiple') {
          this.value.attribute.splice(this.rowIndex, 1)
          return;
        }
        this.$listeners.loadingOpen(true);
        let params = {};

        // 工时记录
        if (this.isHoursRecord) {
          params = { mainId: infoId };

          if(this.needViewDeleteFiles.length){
            params.deleteFiles = JSON.stringify(this.needViewDeleteFiles)
          }
        } else {
          params = {
            taskId: this.task.id,
            cardId: this.card.cardId,
            infoId
          }
          if(this.needViewDeleteFiles.length){
            params.deleteFiles = this.needViewDeleteFiles
          }
        }

        TaskApi[API](params).then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: i18n.t('common.base.deleteSuccess')
            })
            this.isHoursRecord ? this.getHoursRecordList() : this.$emit('initData');
            this.$emit('updateInfoRecord');
            // window.location.href = `/task/view/${this.task.id}`;
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
      } catch(err) {
        console.error(err)
      }
    },
    getDeleteFiles(files){
      this.needServerDeleFiles = [...this.needServerDeleFiles,...files]
    },
    setServerDeleFiles(value){
      this.needServerDeleFiles = value
    },
    addMultipleCardRow() {
      this.$refs.isMultipleCardTable.cleanCache();
      this.$emit('addRow', this.card.cardId, this.columns);
    },
    packMultipleCardRow(data) {
      const { cardId, inputType } = this.card;
      const params = data.map(item => {
        const attribute = {};
        if(['edit', 'delete'].includes(item.operateType)) attribute.id = item.id;
        
        this.card.fields.forEach(field => {
          attribute[field.fieldName] = item[field.fieldName];
        });

        let buildData = {
          taskId: this.task.id,
          cardId,
          inputType,
          operateType: item.operateType,
          attribute,
        };

        buildData = this.globalFormSubmissionDataProcessingHandler(this.card.fields, buildData);
        // 国际化时间处理
        buildData = disposeFormSubmitTime(this.card.fields, buildData);
        
        return buildData;
      });
      return params;
    },
    submitMultipleCardRow(data) {
      this.disabledSaveButton = true;
      const params = this.packMultipleCardRow(data);
      TaskApi.taskBatchSaveOrEdit(params).then(res => {
        if (res.success) {
          this.$message.success(i18n.t('common.base.saveSuccess'));
          this.$emit('initData');
          this.$emit('updateInfoRecord');
          this.$refs.isMultipleCardTable.cleanCache();
        } else {
          this.disabledSaveButton = false;
          this.$message.error(res.message);
          this.$emit('initData');
        }
      }).catch(error => {
        Log.error(error);
      })
    },
    saveAddMultipleCardRow() {
      this.$refs.isMultipleCardTable.saveAddMultipleCardRow();
    },
    updateMultipleCardRow(updateData) {
      this.disabledSaveButton = false;
      this.$emit('update', updateData, this.card.cardId);
    },
    deleteMultipleCardRow(row, index) {
      this.disabledSaveButton = false;
      this.$emit('delete', row, index, this.card.cardId);
    },
    checkMultipleCardDataChange(previous, next) {
      if(!this.disabledSaveButton) {
        MessageBox.confirm(i18n.t('task.tip.notSaveTip'), i18n.t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.save'),
          cancelButtonText: this.$t('common.base.notSaveForNow'),
          type: 'warning',
        })
          .then(async () => {
            this.saveAddMultipleCardRow();
          })
          .catch(error => {
            this.$emit('tabBarChangeItemNext', next);
            Log.warn(error);
          });
      } else {
        this.$emit('tabBarChangeItemNext', next);
      }
    },
  },
  components: {
    [CardEditDialog.name]: CardEditDialog,
    [CardViewDialog.name]: CardViewDialog
  }
}
